import subprocess
import re
import os
from collections import defaultdict
from datetime import datetime
import pandas as pd

def run_git_command(cmd, repo_path):
    """运行 Git 命令并返回输出"""
    try:
        result = subprocess.run(cmd, shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                cwd=repo_path, encoding='utf-8')
        if result.returncode != 0:
            print(f"Git 命令执行失败: {result.stderr}")
            return None
        return result.stdout
    except Exception as e:
        print(f"运行 Git 命令时发生错误: {e}")
        return None


def parse_git_log(since, until, repo_path):
    """解析 Git 日志，统计提交次数、新增和删除行数"""
    cmd = f'git log --since="{since}" --until="{until}" --pretty=format:"%an" --numstat'
    output = run_git_command(cmd, repo_path)

    if not output:
        print(F"{repo_path}没有获取到 Git 日志输出，可能是命令执行失败或者无匹配记录。")
        return {}

    # 使用字典存储每个作者的统计数据
    stats = defaultdict(lambda: {
        "commits": 0,
        "added": 0,
        "removed": 0
    })
    current_author = None

    for line in output.splitlines():
        # 匹配作者名称
        if re.match(r"^[^\t0-9]", line):
            current_author = line.strip()
            stats[current_author]["commits"] += 1
        # 匹配新增和删除行数
        elif re.match(r"^\d", line) and current_author:
            added, removed, _ = line.split('\t')
            stats[current_author]["added"] += int(added)
            stats[current_author]["removed"] += int(removed)

    return stats


def print_stats(stat_list, start_date, end_date):
    """打印统计结果"""
    print(f"统计时间段: {start_date} 到 {end_date}")
    print(f"{'开发者':<20} {'提交次数':<10} {'新增行数':<10} {'删除行数':<10}")
    print("-" * 60)
    result = {}
    for stats in stat_list:
        for author, data in stats.items():
            if author in result:
                df = pd.DataFrame([result[author],data]).fillna(0)  # NaN 填充为 0
                data = df.sum().to_dict()
                result[author] = data
            else:
                result[author] = data

    for author, data in result.items():
        print(f"{author:<20} {data['commits']:<10} {data['added']:<10} {data['removed']:<10}")

def is_git_repo(path):
    """判断指定路径是否是一个 Git 仓库"""
    return os.path.isdir(os.path.join(path, '.git'))


def run_git_pull(repo_path):
    """在指定路径执行 git pull 命令"""
    print(f"更新仓库: {repo_path}")
    try:
        result = subprocess.run(
            ["git", "pull"],
            cwd=repo_path,
            text=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        if result.returncode == 0:
            print(f"更新成功: {repo_path}")
            print(result.stdout)
        else:
            print(f"更新失败: {repo_path}")
            print(result.stderr)
    except Exception as e:
        print(f"执行 git pull 时发生错误: {e}")


file_path = "F:\project\dk-stats"


def read_file_and_update_git():
    """遍历当前目录下的所有 Git 仓库并更新"""
    for folder in os.listdir(file_path):
        repo_path = os.path.join(file_path, folder)
        if os.path.isdir(repo_path) and is_git_repo(repo_path):
            run_git_pull(repo_path)

def stat(start_date,end_date):
    stat_list = []
    for folder in os.listdir(file_path):
        repo_path = os.path.join(file_path, folder)
        # 解析 Git 日志并统计
        stats = parse_git_log(start_date, end_date, repo_path)
        stat_list.append(stats)
    result = {}
    for stats in stat_list:
        for author, data in stats.items():
            if author in result:
                df = pd.DataFrame([result[author], data]).fillna(0)  # NaN 填充为 0
                data = df.sum().to_dict()
                result[author] = data
            else:
                result[author] = data
    return result
if __name__ == "__main__":
    read_file_and_update_git()
    # 设置时间范围
    start_date = input("请输入开始时间 (YYYY-MM-DD): ")
    end_date = input("请输入结束时间 (YYYY-MM-DD): ")

    # 验证日期格式
    try:
        datetime.strptime(start_date, "%Y-%m-%d")
        datetime.strptime(end_date, "%Y-%m-%d")
    except ValueError:
        print("日期格式错误，请使用 YYYY-MM-DD 格式。")
        exit(1)
    stat_list = []
    for folder in os.listdir(file_path):
        repo_path = os.path.join(file_path, folder)
        # 解析 Git 日志并统计
        stats = parse_git_log(start_date, end_date, repo_path)
        stat_list.append(stats)
    #
    # # 打印统计结果
    print_stats(stat_list, start_date, end_date)
